using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;

namespace Macaw.Moss2007.TimerJobServerSelectorSolution
{
    class TimerJobServerSelectorFeature : SPFeatureReceiver
    {



        
        private void ApplyWebConfigModificationsToFarm(SPWebApplication webApp)
        {
            try
            {
                SPWebService.ContentService.WebApplications[webApp.Id].WebService.ApplyWebConfigModifications();
            }
            catch (System.UnauthorizedAccessException ex)
            {
                Trace.WriteLine(string.Format("{2}: Exception occured running the FeatureReceiver when ApplyWebConfigModifications was called.{0}If you give WSS_WPG user account full permission to the config folder the error will disappear!{0}{1}", Environment.NewLine, ex.ToString(), this.GetType().FullName));
                throw;
            }
        }

        private string Owner
        {
            get
            {
                return this.GetType().FullName + ", " + this.GetType().Assembly.FullName;
            }
        }

        private const string TRUSTNODE = "trust";
        private const string FULLVALUE = "Full";

        private SPWebConfigModification AddTrustLevelFull_modification
        {
            get
            {
                SPWebConfigModification modification = new SPWebConfigModification("level", "configuration/system.web/trust");
                modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
                modification.Value = FULLVALUE;
                modification.Owner = Owner;
                return modification;
            }
        }


        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApplication = properties.Feature.Parent as SPWebApplication;
            if (webApplication == null) return;

            SPWebService.ContentService.WebApplications[webApplication.Id].WebConfigModifications.Add(AddTrustLevelFull_modification);

                 SPWebService.ContentService.WebApplications[webApplication.Id].Update();

            ApplyWebConfigModificationsToFarm(webApplication);


            // Make sure the job isn't already registered.
            foreach (SPJobDefinition oldjob in webApplication.JobDefinitions)
            {
                if (oldjob.Name == JobEditControlAdapterJobDefinition.JobName)
                    oldjob.Delete();
            }

            JobEditControlAdapterJobDefinition job = new JobEditControlAdapterJobDefinition(JobEditControlAdapterJobDefinition.JobName, webApplication)
            {
                Installing = true,
                Schedule = new SPOneTimeSchedule(DateTime.Now)
            };
            job.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApplication = properties.Feature.Parent as SPWebApplication;
            if (webApplication == null) return;


            for (int idx = webApplication.WebConfigModifications.Count - 1; idx >= 0; idx--)
            {
                try
                {
                    SPWebConfigModification conmod = SPWebService.ContentService.WebApplications[webApplication.Id].WebConfigModifications[idx];
                    if (string.Compare(conmod.Owner, Owner, true) == 0)
                    {
                        SPWebService.ContentService.WebApplications[webApplication.Id].WebConfigModifications.RemoveAt(idx);
                    }
                }
                catch (Exception ex)
                {
                }
            }

            SPWebService.ContentService.WebApplications[webApplication.Id].Update();

            ApplyWebConfigModificationsToFarm(webApplication);

            // Make sure the job isn't already registered.
            foreach (SPJobDefinition oldjob in webApplication.JobDefinitions)
            {
                if (oldjob.Name == JobEditControlAdapterJobDefinition.JobName)
                    oldjob.Delete();
            }

            JobEditControlAdapterJobDefinition job = new JobEditControlAdapterJobDefinition(JobEditControlAdapterJobDefinition.JobName, webApplication)
            {
                Installing = false,
                Schedule = new SPOneTimeSchedule(DateTime.Now)
            };
            job.Update();
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {

        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {

        }
    }
}
